package router

import (
	"github.com/gin-gonic/gin"
	_"log"
	"net/http"
	. "pdpconv/api"
	. "pdpconv/model"
	_"strconv"
	_"strings"
)

const (
	HEADER_TOKEN string = "client-token"
	HEADER_EXPIRE string = "client-expire"
)



func InitRouter() *gin.Engine{

	// router := gin.Default()
	router := gin.New()

	router.MaxMultipartMemory = 2 << 27
	// 模板文件
	router.LoadHTMLGlob("templates/*")
	// 静态文件
	//获取当前文件的相对路径
	router.Static("/static", "./static")
	//
	//router.StaticFS("/more_static", http.Dir("my_file_system"))
	//获取相对路径下的文件
	//router.StaticFile("/favicon.ico", "./resources/favicon.ico")

	// router.LoadHTMLFiles("templates/index.html","2.html")

	router.Use(gin.Logger())
	router.Use(gin.Recovery())


	router.GET("/index",IndexApi)
	router.POST("/login",Login)

	backend := router.Group("/res")
	backend.Use(AuthBackend())
	{
		backend.GET("/list",ListData)
		backend.POST("/search",FindPageListApi)
		backend.GET("/detail/:id",ShowDocImages)
		backend.GET("/showimage/:fileId",ShowImage)
		backend.POST("upload/",)
		backend.POST("update",)
		backend.DELETE("/del",)
	}

	frontend := router.Group("/upload")
	frontend.Use(AuthFrontend())
	{
		frontend.POST("/doc",UploadDoc)
		frontend.POST("/docs",UploadDocs)
	}

	return router
}

func AuthFrontend() gin.HandlerFunc{
	return func(c *gin.Context){
		// TODO 验证逻辑
		defer func() {
			if recover() != nil {
				c.JSON(http.StatusOK, NewFailedResult2(CODE_FAILED,"系统异常"))
			}
		}()
		c.Next()
	}
}

func AuthBackend() gin.HandlerFunc{
	return func(c *gin.Context){
		// 验证逻辑

		//token := c.GetHeader(HEADER_TOKEN)
		//expire,err := strconv.Atoi(c.GetHeader(HEADER_EXPIRE))
		//if err != nil || expire < 0 || strings.TrimSpace(token) == ""{
		//	log.Panicf("token:[%v] expire:[%v] 验证失败",token,expire)
		//	// 验证错误重定向
		//	c.Redirect(http.StatusMovedPermanently, "/index")
		//	return
		//}
		// TODO 验证token expire


		c.Next()
	}
}